package com.shushan.pages;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.exam.ExamActivity;
import com.shushan.home.bean.LearnByDoBean;
import com.shushan.home.bean.RewardTimeBean;
import com.shushan.home.bean.RewardToyBean;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.ui.VideoView;
import com.shushan.util.DialogUtil;
import com.shushan.util.ImageUtils;
import com.shushan.util.MediaController;
import com.shushan.util.NetWorkUtils;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * @ClassName: StudyWithExerciseActivity
 * @Desciption: //边学边练页面
 * @author: zhangshihao
 * @date: 2018-04-12
 */
@SuppressLint("NewApi")
public class StudyWithExerciseActivity extends NavigationLoseActivity implements View.OnClickListener,
        MediaPlayer.OnCompletionListener,
        View.OnTouchListener,
        MediaController.OnFullScreenClickListener,
        View.OnScrollChangeListener,
        MediaController.OnPauseClickListener
{

    private static final String TAG = StudyWithExerciseActivity.class.getSimpleName();

    //移入视频相关元素@{
    private static final int WIFI = 0;
    private static final int DATA = 1;
    private static final int NO_INTERNET = -1;

    private VideoView videoView;
    private LinearLayout lldataHint;
    private CheckBox checkBox;

    private Button btnCancel;
    private Button btnPlay;
    private Button btnRefresh;
    private ImageView ivVideoBack;
    private ImageView ivFirstFrame;
    private Bitmap firstFrame;

    private boolean noDataHint = false;
    private boolean cantPlayDirectly;

    private static final int PORT_SCREEN = 0;
    private static final int LAND_SCREEN = 1;
    private int screenState = PORT_SCREEN;

    private MediaController mediaController;
    private GestureDetector mGesDetector;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ivFirstFrame.setVisibility(View.VISIBLE);
            ivFirstFrame.setImageBitmap(firstFrame);
        }
    };
    //@}

    //专题名
    private TextView tvSpecialTopicTitle;
    //专题老师
    private TextView tvTeacherName;
    //科目名
    private TextView tvSubjectName;
    //专题描述
    private TextView tvSpecialTopicDes;
    //获得时间奖励条件
    private TextView tvAwardTimeDes;
    //玩具名
    private TextView tvToyName;
    //获得玩具任务完成情况
    private TextView tvAwardToyDes;
    //获得玩具任务描述
    private TextView tvMissionDes;

    private TextView tvAwardTime;

    //专题图片
    private ImageView ivSpecialTopicImg;
    //玩具图片
    private ImageView ivToyPic;

    private View timeLable;
    private View toyLable;

    private Button btnChangeTeacher;
//    private Button btnStartStudy;
    private LinearLayout llTitle;
    private ScrollView scrollView;

    private int subjectId;
    private int position;
    private int addIndex;
    private int videoId;
    private ArrayList<LearnByDoBean> learnByDoBeanList;
    private LearnByDoBean currentLearnByDo;
    private BroadcastReceiver onBackDownReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            onBackAction();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_study_with_exercise);

        setTitle("边学边练");

        subjectId = getIntent().getIntExtra("subjectId",0);
        position = getIntent().getIntExtra("position",0);
        addIndex = position;
        learnByDoBeanList = (ArrayList<LearnByDoBean>) Session.getSession().get("learnByDoBeanList");
        noDataHint = SharedPreferencesUtils.getBooleanDate("noDataHint");

        initView();

        initData(position);
    }

    private void initView(){
        tvSpecialTopicTitle = findViewById(R.id.tv_special_topic_title);
        tvTeacherName = findViewById(R.id.tv_teacher_name);
        tvSubjectName = findViewById(R.id.tv_subject_name);
        tvSpecialTopicDes = findViewById(R.id.tv_special_topic_des);
        tvAwardTime = findViewById(R.id.tv_award_time);
        tvAwardTimeDes = findViewById(R.id.tv_award_time_des);
        tvToyName = findViewById(R.id.tv_toy_name);
        tvAwardToyDes = findViewById(R.id.tv_award_toy_des);
        tvMissionDes = findViewById(R.id.tv_mission_des);
        ivSpecialTopicImg = findViewById(R.id.iv_special_topic_pic);
        ivToyPic = findViewById(R.id.iv_toy_pic);
        btnChangeTeacher = findViewById(R.id.btn_change_teacher);
//        btnStartStudy = findViewById(R.id.btn_start_study);
        timeLable = findViewById(R.id.view_3);
        toyLable = findViewById(R.id.view_4);
        //视频元素@{
        videoView = findViewById(R.id.video_view);
        lldataHint = findViewById(R.id.ll_data_hint);
        btnCancel = findViewById(R.id.btn_cancel);
        btnCancel.setOnClickListener(this);
        btnPlay = findViewById(R.id.btn_play);
        btnPlay.setOnClickListener(this);
        btnRefresh = findViewById(R.id.btn_refresh);
        btnRefresh.setOnClickListener(this);
        checkBox = findViewById(R.id.checkbox);
        //@}
        btnChangeTeacher.setOnClickListener(this);
//        btnStartStudy.setOnClickListener(this);
        mGesDetector = new GestureDetector(this,new MyGestureListener());
        mGesDetector.setOnDoubleTapListener(new MyGestureListener());
        llTitle = findViewById(R.id.ll_title);
        scrollView = findViewById(R.id.scroll_view);
        scrollView.setOnTouchListener(this);
        scrollView.setOnScrollChangeListener(this);
        ivVideoBack = findViewById(R.id.iv_video_back);
        ivVideoBack.setOnClickListener(this);
        mediaController = new MediaController(this);
        ivFirstFrame = findViewById(R.id.iv_first_frame);
    }

    @Override
    public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
        if(mediaController.isShowing()){
            mediaController.hide();
        }
    }

    private boolean isMeetNetConditions() {
        if (getNetworkType() == WIFI || (getNetworkType() == DATA && checkBox.isChecked())) {
            return true;
        }

        return false;
    }

    private int getNetworkType() {
        if (NetWorkUtils.isWifi(this)) {
            return WIFI;
        } else if (NetWorkUtils.isMobile(this)) {
            return DATA;
        }
        return NO_INTERNET;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        DialogUtil.showVideoFinishDialog(this, this);
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(v.getId() == R.id.video_view) {
            return mGesDetector.onTouchEvent(event);
        }else if(v.getId() == R.id.scroll_view){
            if(screenState == LAND_SCREEN){
                return true;//禁止滚动
            }else if(screenState == PORT_SCREEN){
                return super.onTouchEvent(event);//可以滚动
            }
        }
        return super.onTouchEvent(event);
    }

    private void updateUIbyNetworkState() {
        if (getNetworkType() != NO_INTERNET) {
            if (getNetworkType() == WIFI) {
                btnRefresh.setVisibility(View.GONE);
                lldataHint.setVisibility(View.GONE);
                if (!videoView.isPlaying()) {
                    videoView.start();
                }
            } else if (getNetworkType() == DATA) {
                if (noDataHint) {
                    btnRefresh.setVisibility(View.GONE);
                    lldataHint.setVisibility(View.GONE);
                    if (!videoView.isPlaying()) {
                        videoView.start();
                    }
                } else {
                    btnRefresh.setVisibility(View.GONE);
                    lldataHint.setVisibility(View.VISIBLE);
                }
            }
        } else {
            showToast("无网络连接");
            btnRefresh.setVisibility(View.VISIBLE);
            lldataHint.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        updateUIbyNetworkState();

        IntentFilter filter = new IntentFilter(Constants.MEDIA_CONTROLLER_ON_BACK_DOWN_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(onBackDownReceiver,filter);
    }

    @Override
    protected void onStop() {
        super.onStop();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(onBackDownReceiver);
    }

    private void initData(int position) {
        if(ToolUtils.isListEmpty(learnByDoBeanList)){
            return;
        }
        if(getNetworkType() == DATA) {
            if (!SharedPreferencesUtils.getBooleanDate("noDataHint")){
                lldataHint.setVisibility(View.VISIBLE);
                cantPlayDirectly = true;
            }
        }else if(getNetworkType() == NO_INTERNET){
            btnRefresh.setVisibility(View.VISIBLE);
            cantPlayDirectly = true;
        }

        currentLearnByDo = learnByDoBeanList.get(position);
        if(currentLearnByDo != null){
            setFirstFrameDrawable(currentLearnByDo.video_url);

            videoView.setVideoURI(Uri.parse(currentLearnByDo.video_url));
            mediaController.setOnPauseClickListener(this);
            mediaController.setOnFullScreenClickListener(this);
            videoView.setMediaController(mediaController);
            videoView.setOnCompletionListener(this);
            videoView.setOnTouchListener(this);
            videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if(mediaController != null && lldataHint.getVisibility() != View.VISIBLE && btnRefresh.getVisibility() != View.VISIBLE){
                        mediaController.show();
                    }
//                    if (!mp.isPlaying() && isMeetNetConditions()) {
//                        mp.start();
//                    }
                }
            });
            videoId = currentLearnByDo.id;

            tvSpecialTopicTitle.setText(currentLearnByDo.video_title);
            tvTeacherName.setText("讲师： " + currentLearnByDo.video_teacher);
            tvSubjectName.setText("科目： " + ToolUtils.getSubjectNameFromId(subjectId));
            tvSpecialTopicDes.setText(currentLearnByDo.video_desc);

            ImageUtils.loadImageView(this,currentLearnByDo.cover,ivSpecialTopicImg);

        }else {
            showToast("信息为空");
            return;
        }

        RewardTimeBean timeBean = currentLearnByDo.getRewardTimeBean();
        if(timeBean != null && !ToolUtils.isListEmpty(timeBean.timeList)){

            tvAwardTimeDes.setText(RewardTimeBean.getTimeDes(
                    timeBean.timeList.size() - 1, timeBean.timeList.get(timeBean.timeList.size() - 1)));
        }else {
            hideTimeAwardMsg();
        }

        RewardToyBean rewardToyBean = currentLearnByDo.getRewardToyBean();

        if(rewardToyBean == null || TextUtils.isEmpty(rewardToyBean.name)
            || TextUtils.isEmpty(rewardToyBean.description)
            || TextUtils.isEmpty(rewardToyBean.pic)
            || TextUtils.isEmpty(rewardToyBean.task)){

            toyLable.setVisibility(View.GONE);
            ivToyPic.setVisibility(View.GONE);
        }else {
            tvToyName.setText(rewardToyBean.name);
            tvAwardToyDes.setText(rewardToyBean.task);
            tvMissionDes.setText(rewardToyBean.description);

            ImageUtils.loadWXImageView(this,rewardToyBean.pic,ivToyPic);
        }

    }

    private void setFirstFrameDrawable(final String url){
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                Log.d(TAG,"video_url = "+url);
                String loadUrl;
                if(ImageUtils.isAbsoluteUrl(url)){
                    loadUrl = url;
                }else{
                    loadUrl = BuildConfig.imgBaseUrl+url;
                }
                Log.d(TAG,"loadUrl = "+loadUrl);
                try {
                    mmr.setDataSource(loadUrl,new HashMap<String, String>());
                    firstFrame = mmr.getFrameAtTime();
                    mHandler.sendEmptyMessage(0);
                }catch (IllegalArgumentException ex){
                    ex.printStackTrace();
                }catch (RuntimeException ex){
                    ex.printStackTrace();
                } finally {
                    try {
                        mmr.release();
                    } catch (RuntimeException ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }).start();
    }

    @Override
    public void onPauseClick() {
        ivFirstFrame.setVisibility(View.GONE);
    }

    @Override
    public void onFullScreenClick() {
        if (screenState == LAND_SCREEN) {
            convertToPortScreen();
        } else if (screenState == PORT_SCREEN) {
            convertToLandScreen();
        }
    }

    private void hideTimeAwardMsg(){
        tvAwardTime.setVisibility(View.GONE);
        tvAwardTimeDes.setVisibility(View.GONE);
        timeLable.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_change_teacher:
                changeTeacher();
                break;
            case R.id.btn_continue_study://我想再学学
                DialogUtil.dismissDialog();
                break;
            case R.id.btn_start_exercise://学会了，开始练习
                startExam();
                break;
            case R.id.iv_video_back://视频返回按钮
                convertToPortScreen();
                break;
            case R.id.btn_play:
                if (!videoView.isPlaying()) {
                    SharedPreferencesUtils.setBooleanDate("noDataHint", checkBox.isChecked());
                    videoView.start();
                    btnRefresh.setVisibility(View.GONE);
                    lldataHint.setVisibility(View.GONE);
                }
                break;
            case R.id.btn_cancel:
                lldataHint.setVisibility(View.GONE);
                break;
            case R.id.btn_refresh:
                updateUIbyNetworkState();
                break;
            default:
                break;
        }
    }

    private void convertToPortScreen(){
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置videoView竖屏播放
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ToolUtils.dip2px(StudyWithExerciseActivity.this, 198f));
        params.setMargins(ToolUtils.dip2px(StudyWithExerciseActivity.this,12),ToolUtils.dip2px(StudyWithExerciseActivity.this,15),
                ToolUtils.dip2px(StudyWithExerciseActivity.this,12),ToolUtils.dip2px(StudyWithExerciseActivity.this,14));
        //params.addRule(RelativeLayout.CENTER_IN_PARENT);
        videoView.setLayoutParams(params);

        if(ivFirstFrame.getVisibility() == View.VISIBLE) {
            RelativeLayout.LayoutParams ivparams = new RelativeLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ToolUtils.dip2px(StudyWithExerciseActivity.this, 198f));
            ivparams.setMargins(ToolUtils.dip2px(StudyWithExerciseActivity.this, 12), ToolUtils.dip2px(StudyWithExerciseActivity.this, 15),
                    ToolUtils.dip2px(StudyWithExerciseActivity.this, 12), ToolUtils.dip2px(StudyWithExerciseActivity.this, 14));
            //params.addRule(RelativeLayout.CENTER_IN_PARENT);
            ivFirstFrame.setLayoutParams(ivparams);
        }

        screenState = PORT_SCREEN;
        ivVideoBack.setVisibility(View.GONE);
        llTitle.setVisibility(View.VISIBLE);
        btnChangeTeacher.setVisibility(View.VISIBLE);
        showActionBar();
    }

    private void convertToLandScreen(){
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);//设置videoView全屏播放
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//设置videoView横屏播放
        WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
        android.view.Display display = wm.getDefaultDisplay();
        Point point = new Point();
        int API_LEVEL = android.os.Build.VERSION.SDK_INT;
        if(API_LEVEL >= 17){
            display.getRealSize(point);
        }else{
            display.getSize(point);
        }
        int height = point.y;
        int width = point.x;
        Log.i(TAG,"screenHeight = "+height+" ; screenWidth = "+width);
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) videoView
                .getLayoutParams(); // 取控当前的布局参数
        layoutParams.height = height;
        layoutParams.width = width;
        layoutParams.setMargins(0,0,0,0);
        videoView.setLayoutParams(layoutParams);

        if(ivFirstFrame.getVisibility() == View.VISIBLE) {
            RelativeLayout.LayoutParams ivlayoutParams = (RelativeLayout.LayoutParams) ivFirstFrame.getLayoutParams();
            ivlayoutParams.height = height;//设置 当控件的高强
            ivlayoutParams.width = width;
            ivlayoutParams.setMargins(0,0,0,0);
            ivFirstFrame.setLayoutParams(ivlayoutParams);
        }
        screenState = LAND_SCREEN;
        if(mediaController.isShowing()) {
            ivVideoBack.setVisibility(View.VISIBLE);
        }
        llTitle.setVisibility(View.GONE);
        btnChangeTeacher.setVisibility(View.GONE);
        hideActionBar();
    }

    private void startExam() {
        DialogUtil.dismissDialog();
        //onBackAction();

        Intent intent = new Intent(this, ExamActivity.class);
        intent.putExtra("subjectId", subjectId);
        intent.putExtra("videoId", videoId);
        intent.putExtra("awardType", 3);
        startActivityAllow(intent);
    }

    private void changeTeacher() {
        if(ToolUtils.isListEmpty(learnByDoBeanList)){
            showToast("列表为空");
            return;
        }

        int size = learnByDoBeanList.size();
        if(size < 2){
            showToast("没有更多的老师");
            return;
        }

        addIndex++;
        currentLearnByDo = learnByDoBeanList.get(addIndex % size);
        if(currentLearnByDo != null){
            if(videoView.isPlaying()){
                videoView.stopPlayback();
                videoView.setVideoURI(Uri.parse(currentLearnByDo.video_url));
                videoView.start();
            }
            videoId = currentLearnByDo.id;

            tvSpecialTopicTitle.setText(currentLearnByDo.video_title);
            tvTeacherName.setText("讲师： " + currentLearnByDo.video_teacher);
            tvSubjectName.setText("科目： " + ToolUtils.getSubjectNameFromId(subjectId));
            tvSpecialTopicDes.setText(currentLearnByDo.video_desc);

            ImageUtils.loadImageView(this,currentLearnByDo.cover,ivSpecialTopicImg);

        }
    }

    /*
    *
    * 手势监听类
    * */
    class MyGestureListener extends GestureDetector.SimpleOnGestureListener {
        public MyGestureListener() {
            super();
        }
        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (screenState == LAND_SCREEN) {
                convertToPortScreen();
            } else if (screenState == PORT_SCREEN) {
                convertToLandScreen();
            }
            return true;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            if(mediaController.isShowing()){
                if(screenState == LAND_SCREEN) {
                    ivVideoBack.setVisibility(View.GONE);
                }
                mediaController.hide();
            }else{
                if(screenState == LAND_SCREEN) {
                    ivVideoBack.setVisibility(View.VISIBLE);
                }
                mediaController.show();
            }
            return true;
        }

        @Override
        public boolean onContextClick(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public void onShowPress(MotionEvent e) {
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return true;
        }

        @Override
        public void onLongPress(MotionEvent e) {
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return true;
        }
    }

}
